package QRCG;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ChangePersInfoServe
 */
@WebServlet("/ContactServe")
public class ContactServe extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String mailAddress = request.getParameter("mail_address");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");
    // {@code response.sendRedirect} loses request attributes, so {@code
    // RequestDispatcher.forward is used}.
    RequestDispatcher rd = request.getRequestDispatcher("ContactAdmin.jsp");

    boolean success = false;
    if (!Mailer.isValidMailAddress(mailAddress)) {
      request.setAttribute("errorMessage", "The provided mail address is invalid! \n");
    } else if (!Util.hasTextContent(subject) || !Util.hasTextContent(message)) {
      request.setAttribute("errorMessage", "Subject and/or message cannot be empty! \n");
    } else {
      try {
        Mailer.send("CONTACT ADMIN MESSAGE", createContactMessage(mailAddress, subject, message));
        request.setAttribute("informationMessage", "Your message has been sent successfully.");
        success = true;
      } catch (MessagingException me) {
        request.setAttribute("errorMessage", "Your could not be sent. \n");
      }
    }
    // If there is an error in the values provided by the user, keep the values as well as showing
    // the error message.
    if (!success) {
      request.setAttribute("mail_address", mailAddress);
      request.setAttribute("subject", subject);
      request.setAttribute("message", message);
    }
    rd.forward(request, response);
  }

  /**
   * Creates a message for the site administration.
   * @param from The mail address of the sender.
   * @param subject The subject of the message.
   * @param message The body of the message.
   * @return The message to be sent to the site administration.
   */
  private String createContactMessage(String from, String subject, String message) {
    String res = "Sender's mail address: " + from + "\n";
    res += "Subject: " + subject + "\n";
    res += "Body:\n" + message + "\n";
    return res;
  }
}
